package cate.game.server.configuration.part;

import cate.game.client.interceptor.*;

import java.util.ArrayList;
import java.util.List;

public class CommandExecutorBuilder {

    public static CommandExecutor build() throws Exception {
        List<CommandInterceptor> commandInterceptors = initCommandInterceptors();
        CommandInterceptor first = initInterceptorChain(commandInterceptors);
        return new CommandExecutorImpl(first);
    }

    private static List<CommandInterceptor> initCommandInterceptors() {
        List<CommandInterceptor> commandInterceptors = new ArrayList<>();
        commandInterceptors.add(new CountReqsInterceptor());
        commandInterceptors.add(new CostTimeInterceptor());
        commandInterceptors.add(new OperationAdderInterceptor());
        commandInterceptors.add(new ShutupWorldTreeInterceptor());
        commandInterceptors.add(new CommandInvoker());
        return commandInterceptors;
    }

    private static CommandInterceptor initInterceptorChain(List<CommandInterceptor> chain) throws Exception {
        if (chain == null || chain.isEmpty()) {
            throw new Exception("invalid command interceptor chain configuration: " + chain);
        }
        for (int i = 0; i < chain.size() - 1; i++) {
            chain.get(i).setNext(chain.get(i + 1));
        }
        return chain.get(0);
    }
}
